from flask import Flask, request, jsonify
import pymysql
from datetime import datetime

app = Flask(__name__)

# 根路径
@app.route('/')
def home():
    return "Welcome to the Diary App!"

@app.before_request
def before_request():
    print("Received a request")

# 路由定义
@app.route('/diary', methods=['GET', 'POST'])
def diary():
    print("Received a request for /diary")
    if request.method == 'POST':
        # 添加新的日记条目
        data = request.get_json()
        print("Data received for POST:", data)
        date = data.get('date', datetime.now().strftime('%Y-%m-%d'))
        weather = data.get('weather')
        mood = data.get('mood')
        events = data.get('events')

        if not all([weather, mood, events]):
            return jsonify({'error': 'Missing required fields'}), 400

        connection = get_db_connection()
        try:
            with connection.cursor() as cursor:
                sql = """
                    INSERT INTO diary_entries (date, weather, mood, events)
                    VALUES (%s, %s, %s, %s)
                """
                cursor.execute(sql, (date, weather, mood, events))
                connection.commit()
            return jsonify({'message': 'Diary entry added successfully'}), 201
        finally:
            connection.close()

    elif request.method == 'GET':
        # 获取所有日记条目
        connection = get_db_connection()
        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT * FROM diary_entries ORDER BY date DESC")
                entries = cursor.fetchall()
            return jsonify(entries)
        finally:
            connection.close()

def get_db_connection():
    connection = pymysql.connect(
        host='localhost',
        user='root',  # MySQL用户名
        password='123456',  # MySQL密码
        database='diary_db',  # MySQL数据库名称
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
